﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.WindowsAzure.ServiceRuntime;

using Services;

namespace WebRole1
{
	public partial class Register : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
		}


		protected void btnRegister_Click(object sender, EventArgs e)
		{
			if (txtUsername.Text.Trim() == "")
			{
				lblError.Text = "Voer een gebruikersnaam in.";
				return;
			}
			if (txtPassword.Text.Trim() == "")
			{
				lblError.Text = "Voer een wachtwoord in.";
				return;
			}

			if (txtPassword.Text != txtPassword2.Text)
			{
				lblError.Text = "Voer tweemaal hetzelfde wachtwoord in.";
				return;
			}


			//The password of a user is salted and then encrypted with MD5
			//First: get the salt. It is stored in the ServiceConfiguration.cscfg file
			string passwordSalt = RoleEnvironment.GetConfigurationSettingValue("PasswordSalt");

			string hashedPW = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim() + passwordSalt, "MD5");
			UserService userServ = new UserService();
			userServ.InsertUser(txtUsername.Text.Trim(), hashedPW);

			

			//SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLAzureConnection"].ConnectionString);

			//SqlCommand command = conn.CreateCommand();


			//conn.Open();

			//command.CommandText = "select count(*) as usernameCount from users where username = '" + txtUsername.Text.Trim() + "'";
			//command.CommandType = System.Data.CommandType.Text;
			//SqlDataReader dr = command.ExecuteReader();
			//dr.Read();

			//int usernameCount = int.Parse(dr["usernameCount"].ToString());

			//dr.Close();
			//dr.Dispose();


			//if (usernameCount > 0)
			//{
			//   lblError.Text = "De gebruikersnaam is al bezet.";
			//   conn.Close();
			//   return;
			//}


			//string hashedPW = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim() + "9^fk3$d", "MD5");
			//command.CommandText = "insert into users (username, password, recipecount) values ('" + txtUsername.Text.Trim() + "', '" + hashedPW + "', 0)";
			//command.CommandType = System.Data.CommandType.Text;
			//command.ExecuteNonQuery();

			//dr.Close();
			//dr.Dispose();
			//conn.Close();

			Response.Redirect("registerDone.aspx");
		}
	}
}